<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>跨域的解决方式</title>
</head>

<body>
  <script src="https://juejin.cn/post/6844903767226351623#heading-14"></script>
  <script>
    // index.html
    function jsonp({ url, params, callback }) {
      return new Promise((resolve, reject) => {
        let script = document.createElement('script')
        window[callback] = function (data) {
          resolve(data)
          document.body.removeChild(script)
        }
        params = { ...params, callback } // wd=b&callback=show
        let arrs = []
        for (let key in params) {
          arrs.push(`${key}=${params[key]}`)
        }
        script.src = `${url}?${arrs.join('&')}`
        document.body.appendChild(script)
      })
    }
    jsonp({
      url: 'http://localhost:3000/say',
      params: { wd: 'Iloveyou' },
      callback: 'show'
    }).then(data => {
      console.log(data)
    })
  </script>
  <h1>cors</h1>
  <h1>Iframe的postmassage</h1>
  <iframe src="http://localhost:4000/b.html" frameborder="0" id="frame" onload="load()">
  </iframe>
  <script>
    function load() {
      let frame = document.getElementById('frame')
      frame.contentWindow.postMessage('我爱你', 'http://localhost:4000') //发送数据
      window.onmessage = function (e) { //接受返回数据
        console.log(e.data) //我不爱你
      }
    }
  </script>
  <h1>WebSocket</h1>
  <h1>Node中间件代理(两次跨域)</h1>
  <h1>Nginx反向代理</h1>
  <script>
    // proxy服务器
    // server {
    //     listen       81;
    //     server_name  www.domain1.com;
    //     location / {
    //         proxy_pass   http://www.domain2.com:8080;  #反向代理
    //         proxy_cookie_domain www.domain2.com www.domain1.com; #修改cookie里域名
    //         index  index.html index.htm;

    //         # 当用webpack-dev-server等中间件代理接口访问nignx时，此时无浏览器参与，故没有同源限制，下面的跨域配置可不启用
    //         add_header Access-Control-Allow-Origin http://www.domain1.com;  #当前端只跨域不带cookie时，可为*
    //         add_header Access-Control-Allow-Credentials true;
    //     }
    // }
  </script>
  <h1>window.name + iframe</h1>
  <h1>location.hash + iframe</h1>
  <h1>document.domain + iframe</h1>
</body>

</html>